package top.riske.gen3d.common.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import top.riske.gen3d.common.filter.AdminRoleFilter;
import top.riske.gen3d.common.filter.AuthorizationFilter;
import top.riske.gen3d.common.filter.CorsPreFlightFilter;
import top.riske.gen3d.common.filter.UserRoleFilter;


/**
 * 注册过滤器，并指定优先级
 * created by vital on 2025/3/1 下午3:00
 */
@Configuration
public class FilterConfig {

    /**
     * 身份信息提取过滤器
     */
    @Bean
    public FilterRegistrationBean<AuthorizationFilter> authorizationFilter() {
        FilterRegistrationBean<AuthorizationFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new AuthorizationFilter());
        registration.addUrlPatterns("/api/protected/*");
        registration.setOrder(3);// 优先级为第3
        return registration;
    }

    /**
     * 管理员权限过滤器
     */
    @Bean
    public FilterRegistrationBean<AdminRoleFilter> adminRoleFilter() {
        FilterRegistrationBean<AdminRoleFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new AdminRoleFilter());
        registration.addUrlPatterns("/api/protected/admin/*");
        registration.setOrder(5);// 优先级为第5
        return registration;
    }

    /**
     * 用户权限过滤器
     */
    @Bean
    public FilterRegistrationBean<UserRoleFilter> userRoleFilter() {
        FilterRegistrationBean<UserRoleFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new UserRoleFilter());
        registration.addUrlPatterns("/api/protected/user/*");
        registration.setOrder(5);
        return registration;
    }

    /**
     * 跨域请求过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean<CorsPreFlightFilter> corsPreFlightFilter() {
        FilterRegistrationBean<CorsPreFlightFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new CorsPreFlightFilter());
        registration.addUrlPatterns("/*");
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return registration;
    }

}
